package com.edu.util;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;

public class VerifyCode {
	private int width = 70;//背景宽度
	private int heigh = 35;//背景高度
	private Random random = new Random();
	//随机每个字符的字体
	private String[] fontNames = {"宋体","华文楷体","黑体","微软雅黑","楷体_GB2312"};
	//在里面随机出4位验证码
	private String codes = "23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNOPQRSTUVWXYZ";
	private Color bgColor = new Color(255, 255, 255);//背景颜色设置为白色
	private String text;//最终随机出来的文本
	
	//生成随机颜色
	private Color randomColor() {
		int r = random.nextInt(150);
		int g = random.nextInt(150);
		int b = random.nextInt(150);
		return new Color(r, g, b);
	}
	
	//生成随机的字体
	private Font randomFont() {
		int index = random.nextInt(fontNames.length);
		String fontName = fontNames[index];
		int style = random.nextInt(4);//生成随机的字体样式  0(无样式) 1(粗体) 2(斜体) 3(粗体+斜体)
		int size = random.nextInt(5) + 24;//生成随机字号  24 - 28
		return new Font(fontName, style, size);
	}
	
	//划干扰线
	private void drawLine(BufferedImage image) {
		int num = 3;//画三条线
		Graphics2D g2 = (Graphics2D)image.getGraphics();//获取画笔
		for(int i = 0;i < num;i++) {//生成两个点的坐标
			int x1 = random.nextInt(width);
			int y1 = random.nextInt(heigh);
			int x2 = random.nextInt(width);
			int y2 = random.nextInt(heigh);
			g2.setStroke(new BasicStroke(1.5F));
			g2.setColor(Color.BLUE);//画干扰线是蓝色的
			g2.drawLine(x1, y1, x2, y2);//画线
		}
	}
	
	
	//随机生成一个字符
	private char randomChar() {
		int index = random.nextInt(codes.length());
		return codes.charAt(index);
	}
	
	//创建背景
	private BufferedImage createImage() {
		BufferedImage image = new BufferedImage(width, heigh, BufferedImage.TYPE_INT_RGB);
		Graphics2D g2 = (Graphics2D)image.getGraphics();//获取画笔
		g2.setColor(bgColor);
		g2.fillRect(0, 0, width, heigh);
		return image;
	}
	
	//调用这个方法得到处理好的验证码图片
	public BufferedImage getImage() {
		BufferedImage image = createImage();//创建图片缓冲区
		Graphics2D g2 = (Graphics2D)image.getGraphics();//获取画笔/得到绘制环境
		StringBuilder sb = new StringBuilder();//用来装载生成的验证码文本
		//想图片画四个字符
		for(int i = 0;i < 4;i++) {//循环四次,每次生成一个字符
			String s = randomChar() + "";//随机生成一个字母
			sb.append(s);//把字母加到sb中
			float x = i * 1.0F * width / 4;//先把i转成float类型  主要是算出当前字符所占的x轴坐标
			g2.setFont(randomFont());//设置随机字体
			g2.setColor(randomColor());//设置随机颜色
			g2.drawString(s, x, heigh-5);//画单个字符的位置以及画什么字符 ---画图
		}
		text = sb.toString();//把最终生成的字符串给text
		drawLine(image);//添加干扰线
		return image;
	}
	
	//返回验证码图片上的文本
	public String getText() {
		return text;
	}
	
	//保存图片到指定的输出流
	public static void output(BufferedImage image,OutputStream out) throws IOException {
		ImageIO.write(image, "JPEG", out);
	}
}
